from django.shortcuts import render
from django.http import HttpResponse
import os,time
from . models import *

# 分类添加
def typeadd(request):
    # 获取所有的分类
    # types = Types.objects.all()
    # types = Types.objects.raw('select *,concat(path,id) as paths from myadmin_types order by paths;')

    types = Types.objects.extra(select = {'_has':'concat(path,id)'}).order_by('_has')

    for v in types:
        n = v.path.count(',')-1
        v.name = '|----'*n+v.name

    # 分配数据
    context = {"types":types}

    # 加载表单
    return render(request,'myadmin/type/add.html',context)

# 分类添加
def typeinsert(request):

    # 接受数据,进行添加
    ob = Types()
    ob.name = request.POST['name']
    ob.pid = request.POST['pid']

    # 判断当前添加的是否为顶级分类
    if request.POST['pid'] == '0':
        ob.path = '0,'
    else:
        # 根据id查询当前父级分类的path
        t = Types.objects.get(id = request.POST['pid'])
        ob.path = t.path+str(t.id)+','
    
    ob.save()

    return HttpResponse('<script>alert("添加成功");location.href="/admin/type/index";</script>')
    

# 分类列表
def typeindex(request):
    # 获取所有的分类,并排序
    types = Types.objects.extra(select = {'_has':'concat(path,id)'}).order_by('_has')

    for v in types:
        n = v.path.count(',')-1
        v.name = '|----'*n+v.name
        if v.pid == 0:
            v.pname = '顶级分类'
        else:
            t = Types.objects.get(id=v.pid)
            v.pname = t.name

    # 分配数据
    context = {"types":types}

    # 加载模板
    return render(request,'myadmin/type/index.html',context)

# 分类删除
def typedel(request,tid):

    # 判断当前类下是否还有子类
    n = Types.objects.filter(pid = tid).count()

    if n == 0:
        # 没有子类就 执行删除
        ob = Types.objects.get(id = tid)
        ob.delete()
        return HttpResponse('<script>alert("删除成功");location.href="/admin/type/index";</script>')
    else:
        # 如果有子类,不能删除
        return HttpResponse('<script>alert("删除失败,该类下还有子类");location.href="/admin/type/index";</script>')

def typeedit(request,tid):
    # 根据id查询信息
    ob = Types.objects.get(id = tid)

    # 分配数据
    context = {'tinfo':ob}

    # 解析模板
    return render(request,'myadmin/type/edit.html',context)

def typeupdate(request):
    try:
        # 根据id获取对象
        ob = Types.objects.get(id = request.GET['id'])
        ob.name = request.GET['name']
        ob.save()
        return HttpResponse(0)
    except:
        return HttpResponse(1)

